import router, { asyncRoutes } from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import store from '@/store'
import getPageTitle from './utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // 无需登录，可以跳转查看的路由路径

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) { // 登录了
    if (to.path === '/login') { // 不让去login 强制到首页
      next('/')
      NProgress.done()
    } else { // 去其他页面
      next()
      if (!store.getters.name) {
        const menus = await store.dispatch('user/getUserInfoActions')
        console.log(asyncRoutes)
        // menus权限点和路由规则对象匹配
        const filterList = asyncRoutes.filter(routeObj => {
          const routeName = routeObj.children[0].name.toLowerCase()
          return menus.includes(routeName)
        })
        console.log(filterList)
        router.addRoutes(filterList) // 始终都动态添加8个路由规则对象
        filterList.push({ path: '*', redirect: '/404', hidden: true })

        // 给vuex也同步一份
        store.commit('permission/setRoutes', filterList)
        // 路由再跳转一次，因为上面next()会导致白屏（因为放行时，动态路由还没有加入到内存里路由表）
        next({
          path: to.path,
          replace: true // 不让回退
        })
      }
      next()
    }
  } else { // 没登陆
    if (whiteList.includes(to.path)) { // 要去的路由地址是否在白名单出现过
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  // 正常next的走完后
  document.title = getPageTitle(to.meta.title)
  NProgress.done()
})
